package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.WeiXinDemoService;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.util.RestTemplateUtil;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WeiXinDemoServiceImpl implements WeiXinDemoService {
    private Logger logger = LoggerFactory.getLogger(WeiXinDemoServiceImpl.class);
    static String getWechatUsers = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN";

    static String getBatchUser = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=ACCESS_TOKEN";

    @Autowired
    private WxAccessTokenCacheUtils wxAccessTokenCacheUtils;

    @Override
    public void getWechatUser() {

        String accessToken = wxAccessTokenCacheUtils.getAccessToken("2b53ec3f-9c83-11e8-b93d-000c2979eb04", SystemIdEnum.ASSISTANT.getCode(), null);
        log.info("accessToken: {}", accessToken);
        String getWechatUsersFormat = getWechatUsers.replace("ACCESS_TOKEN", accessToken);
        log.info("WeiXinDemoService --> getWechatUsersFormat url: {}", getWechatUsersFormat);

        String result = RestTemplateUtil.get(getWechatUsersFormat);
        log.info("WeiXinDemoService --> getWechatUser result: {}", result);

        JSONObject resultObj = JSONObject.parseObject(result);

        JSONObject dataObj = resultObj.getJSONObject("data");
        JSONArray openIdArray = dataObj.getJSONArray("openid");

        log.info("WeiXinDemoService --> getWechatUser openIds: {}", openIdArray.toJSONString());

        String getBatchUserFormat = getBatchUser.replace("ACCESS_TOKEN", accessToken);
        log.info("getBatchUserFormat url: {}", getBatchUserFormat);

        JSONArray userArray = new JSONArray();
        for(int ii=0; ii<openIdArray.size(); ii++){
            String openId = openIdArray.getString(ii);
            JSONObject userObj = new JSONObject();
            userObj.put("openid", openId);
            userObj.put("lang", "zh_CN");
            userArray.add(userObj);
            if(ii >= 9){
                break;
            }
        }
        log.info("WeiXinDemoService --> get users info: {}", userArray.toJSONString());

        Map<String, Object> userMap = new HashMap<>();
        userMap.put("user_list", userArray);
        String userInfo = RestTemplateUtil.post(getBatchUserFormat, userMap);

        log.info("WeiXinDemoService --> userInfo: {}", userInfo);

    }

}
